package com.gzy.cs3.util;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;

@Component
public class OpenBrowserOnStartup implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        openBrowser("http://localhost:8080/swagger-ui/");
    }

    private void openBrowser(String url) {
        if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
            try {
                Desktop.getDesktop().browse(new URI(url));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Runtime runtime = Runtime.getRuntime();
            try {
                if (System.getProperty("os.name").toLowerCase().contains("win")) {
                    runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
                } else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
                    runtime.exec("open " + url);
                } else if (System.getProperty("os.name").toLowerCase().contains("nix") || System.getProperty("os.name").toLowerCase().contains("nux") || System.getProperty("os.name").toLowerCase().contains("aix")) {
                    runtime.exec("xdg-open " + url);
                } else {
                    System.out.println("无法确定操作系统，无法自动打开浏览器。");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
